import React, { useMemo, useState } from 'react';
import {
  useReactTable,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  getFilteredRowModel,
  ColumnDef,
  flexRender,
  SortingState,
  PaginationState,
  ColumnFiltersState,
} from '@tanstack/react-table';
import { useTranslation } from 'react-i18next';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';

// 定义数据类型
type User = {
  id: number;
  name: string;
  email: string;
  role: string;
  status: 'active' | 'inactive';
  createdAt: string;
};

// 示例数据
const userData: User[] = [
  { id: 1, name: '张三', email: 'zhangsan@example.com', role: '管理员', status: 'active', createdAt: '2023-01-15' },
  { id: 2, name: '李四', email: 'lisi@example.com', role: '用户', status: 'active', createdAt: '2023-02-20' },
  { id: 3, name: '王五', email: 'wangwu@example.com', role: '用户', status: 'inactive', createdAt: '2023-03-10' },
  { id: 4, name: '赵六', email: 'zhaoliu@example.com', role: '编辑', status: 'active', createdAt: '2023-04-05' },
  { id: 5, name: '钱七', email: 'qianqi@example.com', role: '用户', status: 'inactive', createdAt: '2023-05-12' },
  { id: 6, name: '孙八', email: 'sunba@example.com', role: '管理员', status: 'active', createdAt: '2023-06-18' },
];

const AdvancedTableExample: React.FC = () => {
  const { t } = useTranslation();
  const [sorting, setSorting] = useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 5,
  });

  // 定义列
  const columns = useMemo<ColumnDef<User>[]>(
    () => [
      {
        accessorKey: 'id',
        header: t('users.id'),
        size: 50,
      },
      {
        accessorKey: 'name',
        header: t('users.name'),
        size: 150,
      },
      {
        accessorKey: 'email',
        header: t('users.email'),
        size: 200,
      },
      {
        accessorKey: 'role',
        header: t('users.role'),
        size: 100,
      },
      {
        accessorKey: 'status',
        header: t('users.status'),
        size: 100,
        cell: ({ getValue }) => (
          <Badge variant={getValue() === 'active' ? 'default' : 'secondary'}>
            {getValue() === 'active' ? t('users.active') : t('users.inactive')}
          </Badge>
        ),
      },
      {
        accessorKey: 'createdAt',
        header: t('users.createdAt'),
        size: 120,
      },
    ],
    [t]
  );

  // 创建表格实例
  const table = useReactTable({
    data: userData,
    columns,
    state: {
      sorting,
      columnFilters,
      pagination,
    },
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onPaginationChange: setPagination,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
  });

  return (
    <div className="p-4 space-y-4">
      <h2 className="text-xl font-bold">{t('users.title')}</h2>
      
      {/* 搜索框 */}
      <div className="flex items-center py-4">
        <Input
          placeholder={t('users.searchPlaceholder')}
          value={(table.getColumn('name')?.getFilterValue() as string) ?? ''}
          onChange={(event) =>
            table.getColumn('name')?.setFilterValue(event.target.value)
          }
          className="max-w-sm"
        />
      </div>

      {/* 表格容器 */}
      <div className="border rounded-lg overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            {table.getHeaderGroups().map(headerGroup => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map(header => (
                  <th 
                    key={header.id}
                    className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer"
                    onClick={header.column.getToggleSortingHandler()}
                  >
                    {flexRender(
                      header.column.columnDef.header,
                      header.getContext()
                    )}
                    {{
                      asc: ' 🔼',
                      desc: ' 🔽',
                    }[header.column.getIsSorted() as string] ?? null}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {table.getRowModel().rows.length ? (
              table.getRowModel().rows.map(row => (
                <tr key={row.id} className="hover:bg-gray-50">
                  {row.getVisibleCells().map(cell => (
                    <td key={cell.id} className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {flexRender(cell.column.columnDef.cell, cell.getContext())}
                    </td>
                  ))}
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={columns.length} className="h-24 text-center">
                  {t('users.noResults')}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* 分页控件 */}
      <div className="flex items-center justify-between">
        <div className="text-sm text-gray-700">
          {t('users.showing')} {table.getState().pagination.pageIndex * table.getState().pagination.pageSize + 1} {t('users.to')}{' '}
          {Math.min((table.getState().pagination.pageIndex + 1) * table.getState().pagination.pageSize, table.getFilteredRowModel().rows.length)} {t('users.of')}{' '}
          {table.getFilteredRowModel().rows.length} {t('users.results')}
        </div>
        
        <div className="flex space-x-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => table.previousPage()}
            disabled={!table.getCanPreviousPage()}
          >
            {t('users.previous')}
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => table.nextPage()}
            disabled={!table.getCanNextPage()}
          >
            {t('users.next')}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default AdvancedTableExample;